package cn.alise.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;

import common.Logger;

/**
 * ClassName:CSVUtils <br/>
 * Description: 导出csv文件工具类 <br/>
 * Date: 2016年12月29日 上午9:44:48 <br/>
 *
 * @author 陈昊
 * @version 1.0
 * @since JDK 1.7
 * @see
 */
public class CSVUtils {
    
	private static Logger logger = Logger.getLogger(CSVUtils.class);

	/**
	 * 导出CSV文件
	 * @param exportData
	 * @param rowMapper
	 * @param outPutPath
	 * @param filename
	 * @return
	 */
    @SuppressWarnings({ "rawtypes" })
	public static File createCSVFile(List exportData, LinkedHashMap rowMapper, String filename) {
    	
    	UUID uuid = UUID.randomUUID();
    	filename = filename + uuid;
    	
    	// 获取保存路径
    	String outPutPath = PropsUtil.getProperty("lacp.uploadFile.path");
    	// 创建文件
    	File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            csvFile = new File(outPutPath + "/" + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "GB2312"), 1024);
            // 写入文件头部
            for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                csvFileOutputStream.write("\""
                        + propertyEntry.getValue().toString() + "\"");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            csvFileOutputStream.newLine();
            // 写入文件内容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                Object row = (Object) iterator.next();
                for (Iterator propertyIterator = rowMapper.entrySet()
                        .iterator(); propertyIterator.hasNext();) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                    csvFileOutputStream.write("\""
                            + BeanUtils.getProperty(row,propertyEntry.getKey().toString()).toString() + "\"");
                    if (propertyIterator.hasNext()) {
                        csvFileOutputStream.write(",");
                    }
                }
                if (iterator.hasNext()) {
                    csvFileOutputStream.newLine();
                }
            }
            csvFileOutputStream.flush();
        } catch (Exception e) {
            logger.error("Exception", e);
        } finally {
            try {
                csvFileOutputStream.close();
            } catch (IOException e) {
                logger.error("IOException", e);
            }
        }
        return csvFile;
    }
}